import React, { useState, useEffect } from 'react'
import Batchgeneration from './batch/BatchGeneration'
import { Action, SearchForm, TableCard } from 'components';
import { GetlockersList, GetlockTypes, GetAreas, Del_One, Del_Batch } from './service'
import { Table, Select, Input, Button, message, Tag, Popconfirm, Modal } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'

const { confirm } = Modal;
const TableList = ({ setFlag }) => {

  const [dataSource, setDataSource] = useState([]);

  const [Total, setTotal] = useState(0)
  // 加载状态
  const [isFetching, setIsFetching] = useState(false);
  // 物理区
  const [options, setOptions] = useState([]);
  // 柜类型
  const [lockTypes, setLockTypes] = useState([]);
  // 管理区
  const [areas, setAreas] = useState([]);
  // 编辑状态
  const [IsEdit, setIsEdit] = useState(false);
  // 搜索条件
  const [SearchParams, setSearchParams] = useState({
    current: 1,
    pageSize: 10,
    locker_number: "",
    area_name: "",
    locker_type: ""
  });

  useEffect(() => {
    Getdata(SearchParams)

    GetlockTypes().then(data => {

      setLockTypes(data.data.map(item => ({
        label: item.type_name,   // 显示文本
        value: item.type_name,     // 选中值
      })));
    })
    GetAreas().then(data => {
      // console.log("123", data)
      setAreas(data.data.map(item => ({
        label: item.area_name,   // 显示文本
        value: item.id,     // 选中值
      })));
    })
  }, []);

  const Getdata = (params) => {

    setIsFetching(true)
    GetlockersList(params).then(res => {
      console.log(res);
      setDataSource(res.data.list);

      setTotal(res.data.total)
      setIsFetching(false);
    });
  };

  const handleTableChange = (params) => {

    const newParams = { ...SearchParams, current: params.current, pageSize: params.pageSize };
    Getdata(newParams);
    setSearchParams({ ...SearchParams, ...newParams })
  };

  const [selectionIds, setSelectionIds] = useState([]);
  const rowSelection = {
    onChange: (selectedRowKeys) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`);
      setSelectionIds(selectedRowKeys);
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };
  return (
    <div>

      <SearchForm>
        <SearchForm.Item span={8} title="柜号">
          <Input allowClear placeholder="请输入" onChange={(e) => {
            console.log(e.target.value)
            Getdata({ ...SearchParams, locker_number: e.target.value })
            setSearchParams({ ...SearchParams, locker_number: e.target.value })
          }} />
        </SearchForm.Item>

        {/* <SearchForm.Item span={8} title="物理区">
          <Select allowClear placeholder="请选择"

            options={options}
            onChange={(value) => {
              Getdata({ ...SearchParams, physical_zone: value })
              setSearchParams({ ...SearchParams, physical_zone: value })
              console.log(value)
            }}></Select>
        </SearchForm.Item> */}

        <SearchForm.Item span={8} title="柜类型">
          <Select allowClear placeholder="请选择"

            options={lockTypes}
            onChange={(value) => {
              console.log(value)
              Getdata({ ...SearchParams, locker_type: value })
              setSearchParams({ ...SearchParams, locker_type: value })
              console.log(value)
            }}></Select>
        </SearchForm.Item>

        <SearchForm.Item span={8} title="管理区">
          <Select allowClear placeholder="请选择"

            options={areas}
            onChange={(value) => {

              Getdata({ ...SearchParams, area_name: value })
              setSearchParams({ ...SearchParams, area_name: value })
            }}></Select>
        </SearchForm.Item>
        <SearchForm.Item span={8} title="">
          <Button type="primary">查询</Button> &emsp;
          <Button type="primary">重置</Button>
        </SearchForm.Item>

      </SearchForm>
      <TableCard
        loading={isFetching}
        rowKey="id"
        dataSource={dataSource}
        onReload={Getdata}
        onTableChange={handleTableChange}
        rowSelection={{
          type: "checkbox",
          ...rowSelection,
        }}
        actions={[
          <>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setFlag(false)}>批量新建</Button>
            <Button type="danger" disabled={!selectionIds.length} icon={<DeleteOutlined />} onClick={() => {
              confirm({
                title: "确定要删除吗？",
                content: `${selectionIds}`,
                okText: "删除",
                okType: 'danger',
                cancelText: "取消",
                onOk: () => {
                  console.log(selectionIds)
                  let ids = selectionIds.map(item => item.toString())
                  console.log(ids)

                  Del_Batch({ ids }).then(() => {
                    message.success("删除成功");
                    setSelectionIds([]);
                    Getdata({
                      current: 1,
                      pageSize: 10,
                      locker_number: "",
                      physical_zone: "",
                      area_name: "",
                      locker_type: ""
                    })
                  })
                },
                onCancel: () => {

                },
              });
            }}>批量删除</Button>
          </>
        ]}
        pagination={{
          showSizeChanger: true,
          showLessItems: true,
          showTotal: total => `共 ${Total} 条`,
          total: Total,
          current: SearchParams.page,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      >
        <Table.Column title="区号" dataIndex="physical_zone" />
        <Table.Column title="区域" dataIndex="locker_user_type" />
        <Table.Column title="柜号" dataIndex="locker_number" />
        <Table.Column title="柜名" dataIndex="locker_name"  />
        <Table.Column title="在线状态" dataIndex="is_online"
          render={info => {

            return info ? <Tag color="success">在线</Tag > : <Tag color="error">不在线</Tag >
          }} />
        <Table.Column title="柜类型" dataIndex="locker_product_class" />
        <Table.Column title="柜品种" dataIndex="locker_type" />
        <Table.Column title="规格" dataIndex="locker_spec_name" />
        <Table.Column width={180} title="操作" render={info => (
          <Action>

            <Action.Button  >编辑</Action.Button>

            <Popconfirm placement="top" title={`是否删除柜号${info.locker_number}`} onConfirm={() => {
              Del_One(info.id).then((res) => {
                console.log(res)

                if (res.code == 0) {
                  message.success("删除成功")
                  Getdata(SearchParams)
                } else {
                  message.error("删除失败")
                }

              })
            }} okText="删除" cancelText="取消">
              <Action.Button danger


              >删除</Action.Button>
            </Popconfirm>

          </Action>
        )} />
      </TableCard>
    </div>
  )
}

const CabinetSetup = () => {

  const [flag, setFlag] = useState(true)

  return (
    <div>
      {
        flag ? <TableList setFlag={setFlag} /> : <Batchgeneration setFlag={setFlag} />
      }

    </div>
  )
}

export default CabinetSetup